﻿using Surpass.Config;
using Surpass.Model.Dto.ResponseDto.ResponseModel.ResultModel;
using Surpass.Model.WorkFlow;
using Surpass.Repository.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Surpass.Repository.Repository
{
    public class LeaveRepository: DataBase, ILeaveRepository
    {
        private readonly SurpassDbContext _surpassDbContext;
        public LeaveRepository(SurpassDbContext surpassDbContext):base(surpassDbContext)
        {
            _surpassDbContext = surpassDbContext;
        }

        /// <summary>
        /// 添加请假整体流程
        /// </summary>
        /// <param name="leaveRequest"></param>
        /// <returns></returns>
        [DbTransactionInterceptor]
        public async Task<ResponseModel<bool>> LeaveSave(LeaveRequest leaveRequest,long operatorId,string operatorName)
        {
            var count = 0;
            var result = new ResponseModel<bool>();
            //1、添加请假流程
            leaveRequest.Id = Guid.NewGuid();
            await AddAsync(leaveRequest);
            count+=await SaveChangesAsync();
            //2、创建工作流实例
            var flow = new FlowInstance();
            flow.Id = Guid.NewGuid();
            var CreateNode = _surpassDbContext.Nodes.FirstOrDefault(u => u.NodeName.Equals(FlowConstants.CreateFlow));
            //获取当前节点
            flow.NodeSN = CreateNode.NodeSN;
            flow.NodeName = CreateNode.NodeName;
            flow.WFStatus = "已申请";
            flow.OperatorId = operatorId;
            flow.Operator = operatorName;
            flow.StarterId = operatorId;
            flow.Starter = operatorName;
            flow.Operated = operatorName;

            var NextNode = _surpassDbContext.Nodes.FirstOrDefault(u => u.NodeName.Equals(FlowConstants.ApproveFlow));
            flow.ToDoerId = NextNode.OperatorId;
            flow.ToDoer = NextNode.Operator;

            flow.UpdateTime = DateTime.Now;

            flow.RequisitionId = leaveRequest.Id;
            await AddAsync(flow);
            count += await SaveChangesAsync();

            //3、新建流操作记录
            var flowRecord = new FlowRecord();
            flowRecord.Id = Guid.NewGuid();
            flowRecord.WorkId = flow.Id;
            flowRecord.Operator = operatorName;
            flowRecord.OperatorId = operatorId;

            flowRecord.CurrentNodeSN = CreateNode.NodeSN;
            flowRecord.CurrentNode = CreateNode.NodeName;

            flowRecord.IsPass = true;
            flowRecord.IsRead = true;
            flowRecord.UpdateTime = DateTime.Now;
            await AddAsync(flowRecord);
            count += await SaveChangesAsync();
            if (count==3)
            {
                return result.Succeed();
            }
            else
            {
                return result.Fail("添加失败");
            }
        }
    }
}
